@page "/"
@using RestaurantFinder.Core.Models
@using RestaurantFinder.Core.Services
@using Microsoft.JSInterop
@inject IJSRuntime JSRuntime
@inject IRestaurantService RestaurantService
@inject IPageStateService PageStateService
@inject ILogger<Index> Logger
@inject IConfiguration Configuration
@implements IDisposable

<PageTitle>餐厅发现器</PageTitle>

<div class="container-fluid py-4">
    <div class="card shadow-lg">
        <div class="card-header bg-primary text-white">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h1 class="h3 mb-0">
                        <i class="fas fa-utensils me-2"></i>
                        餐厅发现器
                    </h1>
                    <p class="mb-0">让我帮您随机选择附近的美食！</p>
                </div>
                <div class="text-end">
                    <span class="badge @GetDataSourceBadgeClass() fs-6">
                        <i class="@GetDataSourceIcon() me-1"></i>
                        @GetDataSourceText()
                    </span>
                </div>
            </div>
        </div>
        
        <div class="card-body">
            @if (!string.IsNullOrEmpty(_errorMessage))
            {
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    @_errorMessage
                    @if (_errorMessage.Contains("位置") || _errorMessage.Contains("地理"))
                    {
                        <hr />
                        <h6><i class="fas fa-lightbulb me-1"></i> 解决方案：</h6>
                        <ol class="mb-0 small">
                            <li><strong>检查地址栏权限图标：</strong>点击浏览器地址栏的 <i class="fas fa-map-marker-alt text-danger"></i> 或 <i class="fas fa-lock"></i> 图标</li>
                            <li><strong>重置权限：</strong>如果显示"已阻止"，选择"重置权限"或"允许"</li>
                            <li><strong>刷新页面：</strong>重置后请刷新页面重新尝试</li>
                            <li><strong>清除浏览器数据：</strong>在浏览器设置中清除此网站的权限和数据</li>
                            <li><strong>备用方案：</strong> <button class="btn btn-outline-primary btn-sm" @onclick="ShowManualLocationDialog">手动设置位置</button></li>
                        </ol>
                        <div class="mt-2 p-2 bg-light rounded">
                            <small><strong>📱 手机用户：</strong>请确保浏览器有位置权限，并开启设备GPS</small>
                        </div>
                    }
                </div>
            }

            @if (_showLocationPermissionAlert)
            {
                <div class="alert alert-warning alert-dismissible">
                    <i class="fas fa-map-marker-alt me-2"></i>
                    <strong>位置权限被拒绝</strong>
                    <button type="button" class="btn-close" @onclick="() => _showLocationPermissionAlert = false"></button>
                    <hr />
                    <p class="mb-3">
                        <i class="fas fa-info-circle me-1"></i>
                        您拒绝了位置权限请求。为了搜索附近餐厅，请选择以下解决方案：
                    </p>
                    <div class="row g-2">
                        <div class="col-md-6">
                            <div class="card border-info h-100">
                                <div class="card-body text-center">
                                    <i class="fas fa-shield-alt text-info mb-2" style="font-size: 2rem;"></i>
                                    <h6>重新请求权限</h6>
                                    <p class="small text-muted">如果您改变主意</p>
                                    <button class="btn btn-info btn-sm w-100" @onclick="RequestLocationPermission">
                                        <i class="fas fa-location-arrow me-1"></i>
                                        重新请求
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card border-success h-100">
                                <div class="card-body text-center">
                                    <i class="fas fa-map-pin text-success mb-2" style="font-size: 2rem;"></i>
                                    <h6>手动设置位置</h6>
                                    <p class="small text-muted">输入坐标或选择城市</p>
                                    <button class="btn btn-success btn-sm w-100" @onclick="ShowManualLocationDialog">
                                        <i class="fas fa-edit me-1"></i>
                                        手动设置
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                                            <div class="mt-3">
                            <small class="text-muted">
                                <i class="fas fa-lightbulb me-1"></i>
                                <strong>提示：</strong>如果要启用位置权限，请点击浏览器地址栏的 
                                <i class="fas fa-map-marker-alt text-danger"></i> 图标，选择"始终允许"
                            </small>
                            <div class="mt-2">
                                <button class="btn btn-outline-info btn-xs" @onclick="DiagnoseLocationIssue">
                                    <i class="fas fa-stethoscope me-1"></i>
                                    诊断位置问题
                                </button>
                            </div>
                        </div>
                </div>
            }

            @if (_showManualLocationDialog)
            {
                <div class="card border-info mb-4">
                    <div class="card-header bg-info text-white">
                        <h6 class="mb-0">
                            <i class="fas fa-map-pin me-2"></i>
                            手动设置位置
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-5">
                                <label class="form-label">纬度</label>
                                <input type="number" class="form-control" @bind="_manualLatitude" 
                                       step="0.000001" placeholder="例: 39.9042" />
                            </div>
                            <div class="col-md-5">
                                <label class="form-label">经度</label>
                                <input type="number" class="form-control" @bind="_manualLongitude" 
                                       step="0.000001" placeholder="例: 116.4074" />
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button class="btn btn-success w-100" @onclick="UseManualLocation">
                                    <i class="fas fa-check"></i>
                                </button>
                            </div>
                        </div>
                        <div class="mt-3">
                            <small class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                提示：可以在高德地图或百度地图中查看当前位置的经纬度坐标
                            </small>
                            <div class="mt-2">
                                <button class="btn btn-outline-info btn-sm me-2" @onclick="() => UsePresetLocation(39.9042, 116.4074)">
                                    <i class="fas fa-building me-1"></i>北京市中心
                                </button>
                                <button class="btn btn-outline-info btn-sm me-2" @onclick="() => UsePresetLocation(31.2304, 121.4737)">
                                    <i class="fas fa-building me-1"></i>上海市中心
                                </button>
                                <button class="btn btn-outline-info btn-sm me-2" @onclick="() => UsePresetLocation(22.3193, 114.1694)">
                                    <i class="fas fa-building me-1"></i>深圳市中心
                                </button>
                                <button class="btn btn-outline-secondary btn-sm" @onclick="CloseManualLocationDialog">
                                    <i class="fas fa-times me-1"></i>取消
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            }

            <div class="row mb-4">
                <div class="col-md-6">
                    <button class="btn btn-success btn-lg w-100" 
                            @onclick="SearchRestaurants" 
                            disabled="@_isSearching">
                        @if (_isSearching)
                        {
                            <span class="spinner-border spinner-border-sm me-2"></span>
                            <span>搜索中...</span>
                        }
                        else
                        {
                            <i class="fas fa-search me-2"></i>
                            <span>发现附近餐厅</span>
                        }
                    </button>
                    @if (_currentLocation == null && !_isSearching)
                    {
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-info-circle me-1"></i>
                                首次使用需要获取位置权限 
                                @if (!_isSecureContext)
                                {
                                    <span class="text-warning">
                                        | ⚠️ HTTP环境可能无法获取位置
                                    </span>
                                }
                            </small>
                            @if (!_isSecureContext)
                            {
                                <div class="mt-1">
                                    <button class="btn btn-outline-warning btn-sm" @onclick="ShowManualLocationDialog">
                                        <i class="fas fa-map-pin me-1"></i>
                                        直接设置位置
                                    </button>
                                </div>
                            }
                        </div>
                    }
                </div>
                
                <div class="col-md-3">
                    <select class="form-select" @bind="_searchRadius">
                        <option value="500">500米</option>
                        <option value="1000">1公里</option>
                        <option value="2000" selected>2公里</option>
                        <option value="5000">5公里</option>
                    </select>
                </div>

                <div class="col-md-3">
                    <select class="form-select" @bind="_selectedCategory">
                        <option value="餐饮服务">全部美食</option>
                        <option value="中餐厅">中餐</option>
                        <option value="快餐厅">快餐</option>
                        <option value="外国餐厅">外国菜</option>
                        <option value="休闲餐饮场所">休闲餐饮</option>
                    </select>
                </div>
            </div>

            @if (_currentLocation != null)
            {
                <div class="alert alert-info mb-4">
                    <i class="fas fa-map-pin me-2"></i>
                    <strong>当前位置：</strong> 
                    纬度 @_currentLocation.Latitude.ToString("F6")，经度 @_currentLocation.Longitude.ToString("F6")
                </div>
            }

            @if (_selectedRestaurant != null)
            {
                <div class="card border-warning mb-4">
                    <div class="card-header bg-warning text-dark">
                        <h4 class="mb-0">
                            <i class="fas fa-star me-2"></i>
                            🎯 今日推荐餐厅
                        </h4>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <h5 class="card-title">
                                    <i class="fas fa-crown text-warning me-2"></i>
                                    @_selectedRestaurant.Name
                                </h5>
                                <p class="text-muted mb-2">
                                    <i class="fas fa-map-marker-alt me-1"></i>
                                    @_selectedRestaurant.Address
                                </p>
                                <span class="badge bg-primary">
                                    <i class="fas fa-walking me-1"></i>
                                    距离 @GetDistanceText(_selectedRestaurant.Distance)
                                </span>
                                @if (_selectedRestaurant.Rating.HasValue)
                                {
                                    <span class="badge bg-warning text-dark ms-2">
                                        <i class="fas fa-star"></i>
                                        @_selectedRestaurant.Rating.Value.ToString("F1")
                                    </span>
                                }
                            </div>
                            <div class="col-md-4 text-end">
                                <div class="d-flex gap-2 justify-content-end">
                                    <button class="btn btn-outline-warning" 
                                            @onclick="ReselectRecommendedRestaurant"
                                            disabled="@(_isReselecting || !_restaurants.Any())"
                                            title="从搜索结果中重新随机选择">
                                        @if (_isReselecting)
                                        {
                                            <span class="spinner-border spinner-border-sm me-1"></span>
                                        }
                                        else
                                        {
                                            <i class="fas fa-dice me-1"></i>
                                        }
                                        重选
                                    </button>
                                    @if (!string.IsNullOrEmpty(_selectedRestaurant.PhoneNumber))
                                    {
                                        <a href="tel:@_selectedRestaurant.PhoneNumber" 
                                           class="btn btn-success">
                                            <i class="fas fa-phone me-1"></i>
                                            拨号
                                        </a>
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            }

            @if (_restaurants.Any())
            {
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">
                        <i class="fas fa-list me-2"></i>
                        附近发现 @_restaurants.Count 家餐厅
                    </h5>
                    @if (_isStateRestored)
                    {
                        <span class="badge bg-info">
                            <i class="fas fa-history me-1"></i>
                            已恢复上次搜索结果
                        </span>
                    }
                    <button class="btn btn-outline-secondary btn-sm" @onclick="ClearSavedState">
                        <i class="fas fa-refresh me-1"></i>
                        重新搜索
                    </button>
                </div>
                
                <div class="row">
                    @foreach (var restaurant in _restaurants.OrderBy(r => r.Distance))
                    {
                        <div class="col-lg-6 col-xl-4 mb-3">
                            <div class="card h-100 @(restaurant == _selectedRestaurant ? "border-warning bg-light" : "")">
                                <div class="card-body">
                                    <h6 class="card-title">@restaurant.Name</h6>
                                    <p class="text-muted small">@restaurant.Address</p>
                                    <span class="badge bg-primary">
                                        距离 @GetDistanceText(restaurant.Distance)
                                    </span>
                                    @if (restaurant.Rating.HasValue)
                                    {
                                        <span class="badge bg-warning text-dark">
                                            <i class="fas fa-star"></i>
                                            @restaurant.Rating.Value.ToString("F1")
                                        </span>
                                    }
                                    @if (!string.IsNullOrEmpty(restaurant.PhoneNumber))
                                    {
                                        <div class="mt-2">
                                            <a href="tel:@restaurant.PhoneNumber" 
                                               class="btn btn-outline-success btn-sm">
                                                <i class="fas fa-phone"></i>
                                            </a>
                                        </div>
                                    }
                                </div>
                            </div>
                        </div>
                    }
                </div>
            }
        </div>
    </div>
</div>

@code {
    // ========== 页面状态 ==========
    private Location? _currentLocation;
    private List<Restaurant> _restaurants = new();
    private Restaurant? _selectedRestaurant;
    private bool _isSearching = false;
    private string _errorMessage = string.Empty;
    private int _searchRadius = 2000;
    private string _selectedCategory = "餐饮服务";
    
    // ========== 状态驻留相关 ==========
    private bool _isStateRestored = false;
    private Timer? _autoSaveTimer;
    
    // ========== 重选功能相关 ==========
    private bool _isReselecting = false;
    
    // ========== 手动位置设置相关 ==========
    private bool _showLocationPermissionAlert = false;
    private bool _showManualLocationDialog = false;
    private double? _manualLatitude;
    private double? _manualLongitude;
    private bool _isSecureContext = true;

    /// <summary>
    /// 页面初始化 - 尝试恢复之前的状态
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        // 检查安全上下文
        try
        {
            _isSecureContext = await JSRuntime.InvokeAsync<bool>("(() => window.isSecureContext)()");
            Logger.LogInformation("🔒 安全上下文状态: {IsSecure}", _isSecureContext);
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex, "无法检查安全上下文，假设为不安全");
            _isSecureContext = false;
        }
        
        await RestorePageStateAsync();
        
        // 检查地理位置权限状态
        await CheckLocationPermissionAsync();
        
        // 设置自动保存定时器（每30秒保存一次状态）
        _autoSaveTimer = new Timer(async _ => await SavePageStateAsync(), null, 
            TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
    }

    /// <summary>
    /// 🔍 检查地理位置权限状态
    /// </summary>
    private async Task CheckLocationPermissionAsync()
    {
        try
        {
            var permissionState = await JSRuntime.InvokeAsync<string>("checkLocationPermission");
            Logger.LogInformation("📍 地理位置权限状态: {Permission}", permissionState);
            
            // 如果权限被拒绝，显示提示
            if (permissionState == "denied")
            {
                _showLocationPermissionAlert = true;
                StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            Logger.LogWarning(ex, "检查地理位置权限失败");
        }
    }

    /// <summary>
    /// 🎯 核心功能：搜索餐厅并随机推荐 - 使用服务架构
    /// </summary>
    private async Task SearchRestaurants()
    {
        try
        {
            _isSearching = true;
            _errorMessage = string.Empty;
            StateHasChanged();

            // 1. 📍 获取用户地理位置
            _currentLocation = await GetUserLocationAsync();
            
            if (_currentLocation == null)
            {
                Logger.LogWarning("无法获取用户位置，使用默认位置（北京市中心）");
                
                // 如果没有显示位置权限提示，则显示默认错误消息
                if (!_showLocationPermissionAlert)
                {
                    _errorMessage = "无法获取您的位置信息，使用默认位置（北京市中心）进行演示";
                }
                
                _currentLocation = new Location(39.9042, 116.4074);
            }

            // 2. 🍽️ 使用服务搜索附近餐厅
            try
            {
                _restaurants = await RestaurantService.SearchRestaurantsAsync(_currentLocation, _searchRadius);
                Logger.LogInformation("✅ 搜索服务返回 {Count} 家餐厅", _restaurants.Count);
            }
            catch (Exception searchEx)
            {
                Logger.LogError(searchEx, "餐厅搜索服务调用失败");
                _errorMessage = $"搜索餐厅服务暂时不可用：{searchEx.Message}";
                _restaurants = new List<Restaurant>();
                return; // 提前返回，避免后续处理
            }
            
            // 3. 🎲 使用服务随机选择一家目标餐厅
            if (_restaurants.Any())
            {
                try
                {
                    _selectedRestaurant = RestaurantService.SelectRandomRestaurant(_restaurants);
                    
                    if (_selectedRestaurant != null)
                    {
                        Logger.LogInformation("🎯 随机选中餐厅: {RestaurantName}，距离: {Distance}米", 
                            _selectedRestaurant.Name, _selectedRestaurant.Distance);
                    }
                }
                catch (Exception selectEx)
                {
                    Logger.LogError(selectEx, "随机选择餐厅失败");
                    _selectedRestaurant = _restaurants.FirstOrDefault(); // 降级选择第一家
                }
            }
            else
            {
                _errorMessage = "附近没有找到餐厅，请尝试扩大搜索范围或检查网络连接";
                Logger.LogWarning("搜索结果为空，位置: ({Lat}, {Lng}), 半径: {Radius}米", 
                    _currentLocation.Latitude, _currentLocation.Longitude, _searchRadius);
            }

            Logger.LogInformation("搜索完成：找到 {Count} 家餐厅，选中 {Selected}", 
                _restaurants.Count, _selectedRestaurant?.Name ?? "无");

            // 搜索完成后保存状态
            await SavePageStateAsync();
        }
        catch (Exception ex)
        {
            _errorMessage = $"搜索过程中出现错误：{ex.Message}";
            Logger.LogError(ex, "搜索餐厅时发生异常");
        }
        finally
        {
            _isSearching = false;
            _isStateRestored = false; // 新搜索后不再显示恢复状态标记
            StateHasChanged();
        }
    }

    /// <summary>
    /// 📍 通过浏览器API获取用户地理位置
    /// </summary>
    private async Task<Location?> GetUserLocationAsync()
    {
        try
        {
            // 设置超时时间，防止无限等待
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
            var location = await JSRuntime.InvokeAsync<LocationData>("getUserLocation", cts.Token);
            
            // 验证坐标有效性
            if (location.Latitude == 0 && location.Longitude == 0)
            {
                Logger.LogWarning("获取到无效的地理位置坐标 (0,0)");
                return null;
            }
            
            Logger.LogInformation("📍 获取到用户位置: {Lat}, {Lng}", location.Latitude, location.Longitude);
            return new Location(location.Latitude, location.Longitude);
        }
        catch (OperationCanceledException)
        {
            Logger.LogWarning("获取用户位置超时");
            return null;
        }
        catch (JSException jsEx)
        {
            Logger.LogError(jsEx, "JavaScript地理位置API调用失败: {Message}", jsEx.Message);
            return null;
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "获取用户位置失败: {Message}", ex.Message);
            
            // 如果获取位置失败，显示位置权限提示
            var errorMsg = ex.Message.ToLower();
            if (errorMsg.Contains("权限") || errorMsg.Contains("拒绝") || 
                errorMsg.Contains("permission") || errorMsg.Contains("denied") ||
                errorMsg.Contains("安全连接") || errorMsg.Contains("https"))
            {
                _showLocationPermissionAlert = true;
                StateHasChanged(); // 立即更新UI显示权限提示
            }
            
            return null;
        }
    }

    /// <summary>
    /// 🔄 重新请求位置权限
    /// </summary>
    private async Task RequestLocationPermission()
    {
        _showLocationPermissionAlert = false;
        _errorMessage = string.Empty;
        StateHasChanged();
        
        try
        {
            var location = await GetUserLocationAsync();
            if (location != null)
            {
                _currentLocation = location;
                await SearchRestaurants();
            }
            else
            {
                _showLocationPermissionAlert = true;
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "重新请求位置权限失败");
            _errorMessage = $"位置权限请求失败：{ex.Message}";
            _showLocationPermissionAlert = true;
        }
        
        StateHasChanged();
    }

    /// <summary>
    /// 📝 显示手动位置设置对话框
    /// </summary>
    private void ShowManualLocationDialog()
    {
        _showManualLocationDialog = true;
        _showLocationPermissionAlert = false;
        _errorMessage = string.Empty;
        
        // 预填当前位置（如果有的话）
        if (_currentLocation != null)
        {
            _manualLatitude = _currentLocation.Latitude;
            _manualLongitude = _currentLocation.Longitude;
        }
        
        StateHasChanged();
    }

    /// <summary>
    /// ❌ 关闭手动位置设置对话框
    /// </summary>
    private void CloseManualLocationDialog()
    {
        _showManualLocationDialog = false;
        _manualLatitude = null;
        _manualLongitude = null;
        StateHasChanged();
    }

    /// <summary>
    /// ✅ 使用手动输入的位置
    /// </summary>
    private async Task UseManualLocation()
    {
        if (_manualLatitude.HasValue && _manualLongitude.HasValue &&
            _manualLatitude.Value >= -90 && _manualLatitude.Value <= 90 &&
            _manualLongitude.Value >= -180 && _manualLongitude.Value <= 180)
        {
            _currentLocation = new Location(_manualLatitude.Value, _manualLongitude.Value);
            _showManualLocationDialog = false;
            _errorMessage = string.Empty;
            
            Logger.LogInformation("🗺️ 用户手动设置位置: {Lat}, {Lng}", 
                _manualLatitude.Value, _manualLongitude.Value);
                
            await SearchRestaurants();
        }
        else
        {
            _errorMessage = "请输入有效的经纬度坐标（纬度: -90到90，经度: -180到180）";
            StateHasChanged();
        }
    }

    /// <summary>
    /// 🏙️ 使用预设城市位置
    /// </summary>
    private async Task UsePresetLocation(double latitude, double longitude)
    {
        _manualLatitude = latitude;
        _manualLongitude = longitude;
        await UseManualLocation();
    }

    /// <summary>
    /// 🔬 诊断位置问题
    /// </summary>
    private async Task DiagnoseLocationIssue()
    {
        try
        {
            var diagnosis = await JSRuntime.InvokeAsync<object>("diagnoseLocationIssue");
            Logger.LogInformation("🔬 位置诊断完成: {Diagnosis}", System.Text.Json.JsonSerializer.Serialize(diagnosis));
            
            // 显示诊断结果给用户
            _errorMessage = "诊断完成！请查看浏览器控制台(F12)获取详细信息。";
            StateHasChanged();
            
            // 3秒后清除消息
            await Task.Delay(3000);
            _errorMessage = string.Empty;
            StateHasChanged();
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "位置诊断失败");
            _errorMessage = $"诊断失败：{ex.Message}";
        }
    }

    /// <summary>
    /// 获取数据源文本
    /// </summary>
    private string GetDataSourceText()
    {
        var enabledSection = Configuration.GetSection("GaodeMap:Enabled");
        var enabled = bool.TryParse(enabledSection.Value, out var result) && result;
        var hasApiKey = !string.IsNullOrEmpty(Configuration["GaodeMap:ApiKey"]);
        
        if (enabled && hasApiKey)
        {
            return "高德地图数据";
        }
        else
        {
            return "模拟数据";
        }
    }

    /// <summary>
    /// 获取数据源图标
    /// </summary>
    private string GetDataSourceIcon()
    {
        var enabledSection = Configuration.GetSection("GaodeMap:Enabled");
        var enabled = bool.TryParse(enabledSection.Value, out var result) && result;
        var hasApiKey = !string.IsNullOrEmpty(Configuration["GaodeMap:ApiKey"]);
        
        return (enabled && hasApiKey) ? "fas fa-map" : "fas fa-flask";
    }

    /// <summary>
    /// 获取数据源徽章样式
    /// </summary>
    private string GetDataSourceBadgeClass()
    {
        var enabledSection = Configuration.GetSection("GaodeMap:Enabled");
        var enabled = bool.TryParse(enabledSection.Value, out var result) && result;
        var hasApiKey = !string.IsNullOrEmpty(Configuration["GaodeMap:ApiKey"]);
        
        return (enabled && hasApiKey) ? "bg-success" : "bg-secondary";
    }

    /// <summary>
    /// 📏 格式化距离显示
    /// </summary>
    private static string GetDistanceText(double distance)
    {
        if (distance < 1000)
        {
            return $"{distance:F0}米";
        }
        else
        {
            return $"{distance / 1000:F1}公里";
        }
    }

    /// <summary>
    /// 恢复页面状态
    /// </summary>
    private async Task RestorePageStateAsync()
    {
        try
        {
            var savedState = await PageStateService.GetRestaurantDiscoveryStateAsync();
            if (savedState != null && savedState.HasResults)
            {
                _currentLocation = savedState.CurrentLocation;
                _restaurants = savedState.Restaurants;
                _selectedRestaurant = savedState.SelectedRestaurant;
                _searchRadius = savedState.SearchRadius;
                _selectedCategory = savedState.SelectedCategory;
                _isStateRestored = true;

                Logger.LogInformation("🔄 已恢复页面状态：{Count} 家餐厅", savedState.Restaurants.Count);
                StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "恢复页面状态失败");
        }
    }

    /// <summary>
    /// 保存页面状态
    /// </summary>
    private async Task SavePageStateAsync()
    {
        try
        {
            if (_restaurants.Any()) // 只有有搜索结果时才保存
            {
                var state = new RestaurantDiscoveryState
                {
                    CurrentLocation = _currentLocation,
                    Restaurants = _restaurants,
                    SelectedRestaurant = _selectedRestaurant,
                    SearchRadius = _searchRadius,
                    SelectedCategory = _selectedCategory
                };

                await PageStateService.SaveRestaurantDiscoveryStateAsync(state);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "保存页面状态失败");
        }
    }

    /// <summary>
    /// 🎲 重新选择推荐餐厅 - 从现有列表中随机选择
    /// </summary>
    private async Task ReselectRecommendedRestaurant()
    {
        if (!_restaurants.Any())
        {
            _errorMessage = "没有可选择的餐厅，请先搜索附近餐厅";
            return;
        }

        try
        {
            _isReselecting = true;
            _errorMessage = string.Empty;
            StateHasChanged();

            // 添加一点延迟，提升用户体验
            await Task.Delay(300);

            // 使用服务重新随机选择餐厅
            var newSelection = RestaurantService.SelectRandomRestaurant(_restaurants);
            
            if (newSelection != null)
            {
                _selectedRestaurant = newSelection;
                
                Logger.LogInformation("🎲 用户重新选择推荐餐厅: {RestaurantName}，距离: {Distance}米", 
                    _selectedRestaurant.Name, _selectedRestaurant.Distance);

                // 保存新的状态
                await SavePageStateAsync();
                
                // 显示成功反馈（可选，通过临时消息）
                await ShowTemporarySuccessMessage($"已重新为您推荐：{_selectedRestaurant.Name}");
            }
            else
            {
                _errorMessage = "重选失败，请稍后再试";
                Logger.LogWarning("重选餐厅时返回了null结果");
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"重选餐厅时出现错误：{ex.Message}";
            Logger.LogError(ex, "重选推荐餐厅时发生异常");
        }
        finally
        {
            _isReselecting = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 显示临时成功消息
    /// </summary>
    private async Task ShowTemporarySuccessMessage(string message)
    {
        // 临时显示成功消息的简单实现
        var originalError = _errorMessage;
        _errorMessage = string.Empty;
        StateHasChanged();
        
        // 这里可以用更优雅的Toast通知，目前使用日志记录
        Logger.LogInformation("✅ 用户操作反馈: {Message}", message);
        
        await Task.Delay(100); // 确保UI更新
    }

    /// <summary>
    /// 清除保存的状态并重新搜索
    /// </summary>
    private async Task ClearSavedState()
    {
        try
        {
            await PageStateService.ClearRestaurantDiscoveryStateAsync();
            _restaurants.Clear();
            _selectedRestaurant = null;
            _currentLocation = null;
            _errorMessage = string.Empty;
            _isStateRestored = false;
            
            Logger.LogInformation("🗑️ 已清除保存状态，准备重新搜索");
            StateHasChanged();
            
            // 自动触发新的搜索
            await SearchRestaurants();
        }
        catch (Exception ex)
        {
            Logger.LogError(ex, "清除状态失败");
            _errorMessage = $"清除状态失败：{ex.Message}";
        }
    }

    /// <summary>
    /// 页面销毁时清理资源
    /// </summary>
    public void Dispose()
    {
        _autoSaveTimer?.Dispose();
        
        // 页面销毁前最后保存一次状态
        _ = Task.Run(async () =>
        {
            try
            {
                await SavePageStateAsync();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "页面销毁时保存状态失败");
            }
        });
    }

    /// <summary>
    /// JavaScript返回的位置数据结构
    /// </summary>
    private class LocationData
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
}
